package org.ruixue.service;

import org.apache.commons.lang3.StringUtils;
import org.ruixue.dao.oms.EcItemMapper;
import org.ruixue.dao.oms.EcItemSkuMapper;
import org.ruixue.dao.oms.ShopMapper;
import org.ruixue.dao.yshop.StoreProductAttrValueMapper;
import org.ruixue.dao.yshop.StoreProductMapper;
import org.ruixue.entity.oms.EcItem;
import org.ruixue.entity.oms.EcItemSku;
import org.ruixue.entity.oms.Shop;
import org.ruixue.entity.yshop.StoreProduct;
import org.ruixue.entity.yshop.StoreProductAttrValue;
import org.ruixue.entity.yshop.StoreProductAttrValueExample;
import org.ruixue.entity.yshop.StoreProductExample;
import org.ruixue.request.ItemRequest;
import org.ruixue.request.UpdateStockRequest;
import org.ruixue.response.BaseResponse;
import org.ruixue.util.ByteUtil;
import org.ruixue.util.DateUtil;
import org.ruixue.util.SnoGerUtil;
import org.ruixue.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品同步操作
 * 
 * @author 崔棋 2020-04-1
 */
@Service("itemService")
public class ItemService {

	/**
	 * OMS：网店表
	 */
	@Autowired
	private ShopMapper shopMapper;

	/**
	 * OMS：平台商品表
	 */
	@Autowired
	private EcItemMapper ecItemMapper;

	/**
	 * OMS：平台商品SUK表
	 */
	@Autowired
	private EcItemSkuMapper ecItemSkuMapper;

	/**
	 * 平台商城：商品表
	 */
	@Autowired
	private StoreProductMapper storeProductMapper;

	/**
	 * 平台商城：商品SUK表
	 */
	@Autowired
	private StoreProductAttrValueMapper storeProductAttrValueMapper;

	/**
	 * 全部商品下载（三个月内）
	 *
	 * @return
	 */
	public BaseResponse downloadYiItemWhole() throws Exception {
		// 获取当前时间戳
		//Integer startTime = DateUtil.getTimeInMillis(-2);
		//Integer endTime = DateUtil.getTimeInMillis(null);

		// 查询商品数据库-商品表
		StoreProductExample spExample = new StoreProductExample();
		//spExample.createCriteria().andAddTimeBetween(startTime, endTime);
		List<StoreProduct> storeProductList = storeProductMapper.selectByExample(spExample);
		if (storeProductList.size() > 0) {
			// 将商品ID存储在LIST集合中
			List<Integer> productIdList = new ArrayList<Integer>();
			productIdList = storeProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());

			// 查询商品对应SUK详细信息
			StoreProductAttrValueExample spavExample = new StoreProductAttrValueExample();
			spavExample.createCriteria().andProductIdIn(productIdList);
			List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueMapper
					.selectByExample(spavExample);

			// 保存商品和商品SUK
			BaseResponse baseResponse = downloadSuningItemSaveData(null, storeProductList, storeProductAttrValueList);
			if (baseResponse.getSuccess().equals("false")) {
				return baseResponse;
			}
		}
		return new BaseResponse();
	}

	/**
	 * 商品下载 按时间段 增量
	 *
	 * @param shopId
	 * @return
	 */
	public BaseResponse downloadYiItem(String shopId) throws Exception {
		if (StringUtils.isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		long time = DateUtil.formatStringToDate(DateUtil.formatDateToString(shop.getJobEcItemLastUpdateTime()))
				.getTime();
		// 开始时间
		Integer startTime = DateUtil.getTimeMillis(time);
		// 结束时间
		Integer endTime = DateUtil.getTimeMillis(System.currentTimeMillis());

		// 查询商品数据库-商品表
		StoreProductExample spExample = new StoreProductExample();
		spExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey())) // 使用网店表中的AppKey保存对应商城商户ID
				.andAddTimeBetween(startTime, endTime);
		List<StoreProduct> storeProductList = storeProductMapper.selectByExample(spExample);
		if (storeProductList.size() > 0) {
			// 将商品ID存储在LIST集合中
			List<Integer> productIdList = new ArrayList<Integer>();
			productIdList = storeProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());

			// 查询商品对应SUK详细信息
			StoreProductAttrValueExample spavExample = new StoreProductAttrValueExample();
			spavExample.createCriteria().andProductIdIn(productIdList);
			List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueMapper
					.selectByExample(spavExample);

			// 保存商品和商品SUK
			BaseResponse baseResponse = downloadSuningItemSaveData(shop, storeProductList, storeProductAttrValueList);
			if (baseResponse.getSuccess().equals("false")) {
				return baseResponse;
			}
		}

		// 更新操作时间
		Shop shopUpdate = new Shop();
		shopUpdate.setShopId(shop.getShopId());
		shopUpdate.setJobEcItemLastUpdateTime(DateUtil.formatStringToDate(DateUtil.getCurrentDateStr()));
		shopMapper.updateByPrimaryKeySelectiveShop(shopUpdate);

		return new BaseResponse();
	}

	/**
	 * 按店铺全部商品同步
	 * 
	 * @param shopId
	 * @return
	 * @throws ParseException
	 */
	public BaseResponse downloadYiItemAll(String shopId) throws ParseException {
		if (StringUtils.isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 查询商品数据库-商品表
		StoreProductExample spExample = new StoreProductExample();
		// 使用网店表中的AppKey保存对应商城商户ID
		spExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey()));
		List<StoreProduct> storeProductList = storeProductMapper.selectByExample(spExample);
		if (storeProductList.size() > 0) {
			// 将商品ID存储在LIST集合中
			List<Integer> productIdList = new ArrayList<Integer>();
			productIdList = storeProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());

			// 查询商品对应SUK详细信息
			StoreProductAttrValueExample spavExample = new StoreProductAttrValueExample();
			spavExample.createCriteria().andProductIdIn(productIdList);
			List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueMapper
					.selectByExample(spavExample);

			// 保存商品和商品SUK
			BaseResponse baseResponse = downloadSuningItemSaveData(shop, storeProductList, storeProductAttrValueList);
			if (baseResponse.getSuccess().equals("false")) {
				return baseResponse;
			}
		}
		return new BaseResponse();
	}

	/**
	 * 按店铺中平台商品编码
	 * 
	 * @param ecItemCode
	 *            平台商品编码
	 * @return
	 * @throws ParseException
	 */
	public BaseResponse downloadYiEcItemCode(String ecItemCode) throws ParseException {
		// 根据平台商品编码-查询商品对应的网店
		EcItem ecItem = ecItemMapper.selectEcItemByEcItemCode(ecItemCode);
		if (ecItem == null) {
			return new BaseResponse("false", "ecItem is null");
		}
		// OuterCode 储存商品ID
		Shop shop = shopMapper.selectByPrimaryKeyAppKey(ecItem.getOuterCode());
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 查询商品数据库-商品表
		StoreProductExample spExample = new StoreProductExample();
		spExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey())) // 使用网店表中的AppKey保存对应商城商户ID
				.andIdEqualTo(Integer.parseInt(ecItemCode)); // 商品ID
		List<StoreProduct> storeProductList = storeProductMapper.selectByExample(spExample);
		if (storeProductList.size() > 0) {
			// 将商品ID存储在LIST集合中
			List<Integer> productIdList = new ArrayList<Integer>();
			productIdList = storeProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());

			// 查询商品对应SUK详细信息
			StoreProductAttrValueExample spavExample = new StoreProductAttrValueExample();
			spavExample.createCriteria().andProductIdIn(productIdList);
			List<StoreProductAttrValue> storeProductAttrValueList = storeProductAttrValueMapper
					.selectByExample(spavExample);

			// 保存商品和商品SUK
			BaseResponse baseResponse = downloadSuningItemSaveData(shop, storeProductList, storeProductAttrValueList);
			if (baseResponse.getSuccess().equals("false")) {
				return baseResponse;
			}
		}
		return new BaseResponse();
	}

	/**
	 * 商品上架
	 *
	 * @param shopId
	 * @param itemRequest
	 * @return
	 */
	public BaseResponse listingYiItem(String shopId, ItemRequest itemRequest) throws ParseException {
		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}
		// 修改商品状态（0：未上架，1：上架）
		return updateStoreProduct(shop, itemRequest, 1);
	}

	/**
	 * 商品下架
	 *
	 * @param shopId
	 * @param itemRequest
	 * @return
	 */
	public BaseResponse delistingYiItem(String shopId, ItemRequest itemRequest) throws ParseException {
		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}
		// 修改商品状态（0：未上架，1：上架）
		return updateStoreProduct(shop, itemRequest, 0);
	}

	/**
	 * 商品同步库存
	 *
	 * @param shopId
	 * @param updateYiSkuStock
	 * @return
	 */
	public BaseResponse updateYiSkuStock(String shopId, UpdateStockRequest updateStockRequest) throws ParseException {
		if (isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 库存量
		Integer stockCount = Integer.parseInt(updateStockRequest.getStockCount());

		// 因ecSkuCode中，存储商品表主键ID或商品SUK表编码
		try {
			// ID查询商品表
			Integer id = Integer.parseInt(updateStockRequest.getEcSkuCode());
			StoreProduct storeProduct = storeProductMapper.selectByPrimaryKey(id);
			storeProduct.setStock(stockCount);
			// 修改商品表库存量
			int record = storeProductMapper.updateByPrimaryKeySelective(storeProduct);
			if (record < 0) {
				return new BaseResponse("false", "api is error: " + updateStockRequest.getEcSkuCode());
			}
		} catch (Exception ex) {
			// 编码查询商品SUK表
			StoreProductAttrValueExample spavExample = new StoreProductAttrValueExample();
			spavExample.createCriteria().andUniqueEqualTo(updateStockRequest.getEcSkuCode());
			List<StoreProductAttrValue> spavList = storeProductAttrValueMapper.selectByExample(spavExample);
			if (spavList.size() > 0) {
				// 修改商品SUK表库存量
				StoreProductAttrValue storeProductAttrValue = spavList.get(0);
				storeProductAttrValue.setStock(stockCount);
				int record = storeProductAttrValueMapper.updateByPrimaryKeySelective(storeProductAttrValue);
				if (record < 0) {
					return new BaseResponse("false", "api is error: " + updateStockRequest.getEcSkuCode());
				}
				// 合计总库存量
				int stockTotalCount = stockCount;
				// 根据商品ID查询
				spavExample = new StoreProductAttrValueExample();
				spavExample.createCriteria().andProductIdEqualTo(storeProductAttrValue.getProductId())
						.andUniqueNotEqualTo(updateStockRequest.getEcSkuCode());
				spavList = storeProductAttrValueMapper.selectByExample(spavExample);
				for (int i = 0; i < spavList.size(); i++) {
					StoreProductAttrValue spav = spavList.get(i);
					stockTotalCount = stockTotalCount + spav.getStock();
				}
				// 修改商品表库存量
				StoreProduct storeProduct = storeProductMapper.selectByPrimaryKey(storeProductAttrValue.getProductId());
				storeProduct.setStock(stockTotalCount);
				// 修改商品表库存量
				record = storeProductMapper.updateByPrimaryKeySelective(storeProduct);
				if (record < 0) {
					return new BaseResponse("false", "api is error: " + updateStockRequest.getEcSkuCode());
				}
			}
		}
		return new BaseResponse();
	}

	/**
	 * 修改商品状态
	 * 
	 * @param shop
	 *            商户ID
	 * @param itemRequest
	 *            商品ID
	 * @param isShow
	 *            （0：未上架，1：上架）
	 * @return
	 */
	private BaseResponse updateStoreProduct(Shop shop, ItemRequest itemRequest, int isShow) {
		// 修改平台商品表状态
		StoreProductExample spExample = new StoreProductExample();
		spExample.createCriteria().andIdEqualTo(Integer.parseInt(itemRequest.getEcItemCode())) // 商品ID
				.andMerIdEqualTo(Integer.parseInt(shop.getAppKey())); // 商户ID
		List<StoreProduct> storeProductList = storeProductMapper.selectByExample(spExample);
		if (storeProductList.size() > 0) {
			StoreProduct storeProduct = storeProductList.get(0);
			storeProduct.setIsShow((byte) isShow);
			storeProductMapper.updateByPrimaryKeySelective(storeProduct);
		} else {
			return new BaseResponse("false", "api is error");
		}
		return new BaseResponse();
	}

	/**
	 * 保存商品数据
	 * 
	 * @param shop
	 *            网店
	 * @param storeProductList
	 *            商品集合
	 * @param storeProductAttrValueList
	 *            商品SUK集合
	 * @return
	 */
	private BaseResponse downloadSuningItemSaveData(Shop shop, List<StoreProduct> storeProductList,
			List<StoreProductAttrValue> storeProductAttrValueList) {
		// 循环商品保存集合
		for (int i = 0; i < storeProductList.size(); i++) {
			StoreProduct storeProduct = storeProductList.get(i);
			if (shop == null) {
				shop = shopMapper.selectByPrimaryKeyAppKey(storeProduct.getMerId().toString());
				if (shop == null) {
					return new BaseResponse("false", "shop is null");
				}
			}
			EcItem ecItem = new EcItem();
			ecItem.setEcItemId(SnoGerUtil.getUUID());
			ecItem.setEcItemCode(storeProduct.getId().toString());
			ecItem.setEcItemName(storeProduct.getStoreName());
			ecItem.setOuterCode(storeProduct.getId().toString());
			ecItem.setPrjId(shop.getPrjId());
			ecItem.setShopId(shop.getShopId());
			ecItem.setShopName(shop.getShopName());
			ecItem.setShopAccount(shop.getShopAccount());
			ecItem.setShopType(shop.getShopType());
			ecItem.setItemUrl("");
			ecItem.setSalePrice(storeProduct.getPrice());
			ecItem.setPostFee(storeProduct.getPostage());
			ecItem.setRemark(storeProduct.getDescription());
			ecItem.setApproveStatus(ByteUtil.byteToInt(storeProduct.getIsShow()) == 1 ? "上架" : "下架");
			ecItem.setDeleted(ByteUtil.byteToInt(storeProduct.getIsDel()) == 0 ? "n" : "y");
			ecItem.setOtPrice(storeProduct.getOtPrice());
			ecItem.setCost(storeProduct.getCost());
			
			// 插入数据 平台商品表
			EcItem ecItemModel = ecItemMapper.selectByPrimaryKeyEcItem(ecItem);
			if (ecItemModel == null) {
				ecItemMapper.insertSelectiveEcItem(ecItem);
			} else {
				ecItemMapper.updateByPrimaryKeySelectiveEcItem(ecItem);
			}

			// 关联商品计数器
			int iTemp = 0;

			// 商品SUK明細保存
			List<StoreProductAttrValue> spavList = storeProductAttrValueList.stream()
					.filter(s -> s.getProductId().equals(storeProduct.getId())).collect(Collectors.toList());

			// 判断如果商品没有SKU数据时
			if (spavList.size() <= 0) {
				EcItemSku ecItemSku = new EcItemSku();
				ecItemSku.setEcSkuId(SnoGerUtil.getUUID());
				ecItemSku.setEcItemId(ecItem.getEcItemId());
				ecItemSku.setShopId(ecItem.getShopId());
				ecItemSku.setEcItemCode(ecItem.getEcItemCode());
				ecItemSku.setEcSkuCode(ecItem.getEcItemCode());
				ecItemSku.setEcSkuName(ecItem.getEcItemName());
				ecItemSku.setOuterCode(ecItem.getOuterCode());
				ecItemSku.setSalePrice(ecItem.getSalePrice());
				ecItemSku.setQty(Long.valueOf(storeProduct.getStock()));
				ecItemSku.setAutoStock("y");
				ecItemSku.setOtPrice(ecItem.getOtPrice());
				ecItemSku.setCost(ecItem.getCost());
				
				// 插入数据 平台商品明细表
				EcItemSku ecItemSkuModel = ecItemSkuMapper.selectByPrimaryKeyEcItemSku(ecItemSku);
				if (ecItemSkuModel == null) {
					ecItemSkuMapper.insertSelectiveEcItemSku(ecItemSku);
				} else {
					ecItemSkuMapper.updateByPrimaryKeySelectiveEcItemSku(ecItemSku);
					// 判断该平台商品是否关联系统商品
					if ("y".equals(ecItemSkuModel.getIsGroup()) || "n".equals(ecItemSkuModel.getIsGroup())
							&& StringUtils.isNotBlank(ecItemSkuModel.getSkuId())) {
						String relateStatus = "all";
						// 更新平台商品关联状态
						EcItem ecItemUpdate = new EcItem();
						ecItemUpdate.setEcItemCode(ecItem.getEcItemCode());
						ecItemUpdate.setShopId(ecItem.getShopId());
						ecItemUpdate.setRelateStatus(relateStatus);
						ecItemMapper.updateByPrimaryKeySelectiveEcItem(ecItemUpdate);
					}
				}
			} else {
				// 删除sku 平台表 deleted = 'y'
				EcItemSku ecItemSkuDelete = new EcItemSku();
				ecItemSkuDelete.setShopId(ecItem.getShopId());
				ecItemSkuDelete.setEcItemCode(ecItem.getEcItemCode());
				ecItemSkuMapper.deleteByPrimaryKeyEcItemSku(ecItemSkuDelete);

				for (int j = 0; j < spavList.size(); j++) {
					StoreProductAttrValue storeProductAttrValue = spavList.get(j);

					EcItemSku ecItemSku = new EcItemSku();
					ecItemSku.setEcSkuId(SnoGerUtil.getUUID());
					ecItemSku.setEcItemId(ecItem.getEcItemId());
					ecItemSku.setShopId(ecItem.getShopId());
					ecItemSku.setEcItemCode(ecItem.getEcItemCode());
					ecItemSku.setEcSkuCode(storeProductAttrValue.getUnique());
					ecItemSku.setEcSkuName(storeProductAttrValue.getSuk());
					ecItemSku.setOuterCode(storeProductAttrValue.getUnique());
					ecItemSku.setSalePrice(storeProductAttrValue.getPrice());
					ecItemSku.setQty(Long.valueOf(storeProductAttrValue.getStock()));
					ecItemSku.setDeleted(ecItem.getDeleted());
					ecItemSku.setGoodsName(ecItem.getEcItemName());
					ecItemSku.setOtPrice(ecItem.getOtPrice());
					ecItemSku.setCost(storeProductAttrValue.getCost());
					
					// 插入数据 平台商品明细表
					EcItemSku ecItemSkuModel = ecItemSkuMapper.selectByPrimaryKeyEcItemSku(ecItemSku);
					if (ecItemSkuModel == null) {
						ecItemSkuMapper.insertSelectiveEcItemSku(ecItemSku);
					} else {
						ecItemSkuMapper.updateByPrimaryKeySelectiveEcItemSku(ecItemSku);
						// 判断该平台商品是否关联系统商品
						if ("y".equals(ecItemSkuModel.getIsGroup())) {
							iTemp++;
						} else if ("n".equals(ecItemSkuModel.getIsGroup())
								&& StringUtils.isNotBlank(ecItemSkuModel.getSkuId())) {
							iTemp++;
						}
					}
				}
			}

			// 关联状态(all、none、part) default: none
			String relateStatus = "none";
			if (iTemp > 0) {
				if (iTemp == spavList.size()) {
					// 全部关联系统商品
					relateStatus = "all";
				} else {
					// 部分关联系统商品
					relateStatus = "part";
				}

				// 更新平台商品关联状态
				EcItem ecItemUpdate = new EcItem();
				ecItemUpdate.setEcItemCode(ecItem.getEcItemCode());
				ecItemUpdate.setShopId(ecItem.getShopId());
				ecItemUpdate.setRelateStatus(relateStatus);
				ecItemMapper.updateByPrimaryKeySelectiveEcItem(ecItemUpdate);
			}
		}
		return new BaseResponse();
	}
}